package ltd.dujiabao.cache_processor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Optional;

import com.alibaba.fastjson.JSON;

/**
 * @author : DuJiabao
 * @Project : cache_processor
 * @Time : 2022/1/15 10:57
 * @Desc :
 */

public class Application {
    public static final String SERIES_INFO_SUFFIX = ".dvi";

    public static void main(String[] args) throws IOException {
        String cacheDir = "F:\\bilibili cache\\967612226";
        String outputDir = "F:\\学习视频";
        Path path = Paths.get(cacheDir);
        Optional<String> title = getTitle(path);
        if (!title.isPresent()) {
            return;
        }
        String subDirName = title.get();
        subDirName = PathUtils.replaceAllIllegalChar(subDirName);
        Files.list(path)
                .filter(Files::isDirectory)
                .forEach(new SinglePartProcessor(outputDir + File.separator + subDirName));
    }


    private static Optional<String> getTitle(Path path) {
        Optional<Path> firstPathEndWiths = PathUtils.findFirstPathEndWiths(path, SERIES_INFO_SUFFIX);
        if (firstPathEndWiths.isPresent()) {
            Optional<String> info = PathUtils.readFile(firstPathEndWiths.get());
            if (info.isPresent()) {
                Map<String, String> map = JSON.parseObject(info.get(), Map.class);
                return Optional.of(map.get("Title"));
            }
        }
        return Optional.empty();
    }
}
